package com.zrfintech.api.aop;

import com.google.common.collect.Maps;
import com.zrfintech.common.RequestContext;
import com.zrfintech.common.util.MDCUtils;
import com.zrfintech.common.util.SpringContextUtil;
import com.zrfintech.api.service.RequestContextService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import java.io.IOException;
import java.util.Map;

@Component
@Order(2)
public class CleanupFilter implements Filter {

    private static Logger logger = LoggerFactory.getLogger(CleanupFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("Init CleanupFilter, loading .....");
    }

    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
            throws IOException,
            ServletException {
        Map<String, Object> map = Maps.newHashMap();
        map.put("xx", "xx");
        RequestContext.set(map);
        chain.doFilter(request, response);
        // 数据保存放到最后,先返回业务数据再处理上下文&计费
        RequestContextService contextService = SpringContextUtil.getBean("requestContextService");
        contextService.requestAfter();
        RequestContext.remove();
        MDCUtils.clear();
    }

    @Override
    public void destroy() {

    }

}
